import {wxLogin,mobileLogin} from '../../apis/index'
import { Toast,SetStorage } from '../../tool/wx.public'
Component({

    /**
     * 组件的属性列表
     */
    properties: {

    },

    /**
     * 组件的初始数据
     */
    data: {
        isdisabled: false,
    },

    /**
     * 组件的方法列表
     */
    methods: {
        OffLogin() {
            this.triggerEvent('cloasLogin','showlogin')
        },
        async wxLogin() {
            var This = this
          const logincode = await  getApp().globalData.wxLogin()
          if(logincode.errMsg == 'login:ok'){
            const code = logincode.code
            wxLogin({code}).catch(err=>{
                Toast(err.mes)
            }).then(data=>{
                if(data.hasOwnProperty('token') && data.hasOwnProperty('uInfo')){
                    const {token,uInfo,study} = data
                    SetStorage('token',token)
                    SetStorage('userData',uInfo)
                    SetStorage('study',study)
                    This.triggerEvent('loginOk',uInfo)
                }
            })
          }
        },
        getPhoneNumber: async function (detail) {
            this.setData({
                isdisabled: true,
                agree: true
            })
            wx.showLoading({ title: '加载中...' })
            const logincode = await  getApp().globalData.wxLogin(), code = logincode.code;
            if (detail.detail.errMsg === 'getPhoneNumber:ok' && logincode.errMsg == 'login:ok') {
                var start = wx.getPerformance().now();
                console.log(JSON.stringify(detail.detail))
                const {code:codephone} = detail.detail
                            
                  const userData = await mobileLogin({code,codephone}).catch(err=>{
                    Toast(err.mes)
                  })
                  wx.hideLoading()
                  if(userData.hasOwnProperty('token') && userData.hasOwnProperty('uInfo')){
                    const {token,uInfo,study} = userData
                    SetStorage('token',token)
                    SetStorage('userData',uInfo)
                    SetStorage('study',study)
                    this.triggerEvent('loginOk',uInfo)
                  }
                var end = wx.getPerformance().now();
                console.warn('UserAuth封装调用登录函数，整个登录耗时', `${end - start}ms`)
                this.setData({
                    isdisabled: false,
                })
            } else {
                wx.hideLoading()
                // 拒绝授权手机号码
                if (detail.detail.errMsg === "getPhoneNumber:fail user deny") {
                    wx.hideLoading()
                    this.setData({
                        isdisabled: false,
                    })
                    return false
                }
                this.setData({
                    isdisabled: false,
                })
            }
        },
    }
})